import time

from flask import Blueprint, request, redirect, make_response, Response, jsonify, render_template
from application.models.model import User, Role, role_user, BrokerUser, News
from db_init import db
from swaager_init import siwa, BaseModel
from sqlalchemy import text
from flask_login import current_user, login_required

from tools.data_tools import orm2dict, ret_route, limit_offset

news_blue = siwa.blueprint("news", __name__)


@news_blue.route("/", methods=['get'])
def news():
    order = request.args.get('order', 'id')
    news_type = request.args.get('news_type')
    limit, offset = limit_offset(dict(request.args))

    sql = News.query

    # 传了 类型的sql
    if news_type:
        sql = sql.filter_by(news_type=news_type)

    orm_data = sql.order_by(text(f'-top,{order}')).limit(limit) \
        .offset(offset * limit).all()

    ret_data = orm2dict(orm_data)

    for orm, dic in zip(orm_data, ret_data):
        dic['user'] = orm2dict(orm.zuozhe, filter=['password'])
        dic['course'] = orm2dict(orm.course)

    return ret_route(data=ret_data)


@news_blue.route("/<int:new_id>", methods=['get'])
def get_new(new_id):
    news_data = News.query.get(new_id)
    # ret_data = orm2dict(news_data)
    # ret_data['user_name'] = news_data.zuozhe.nikename
    # ret_data['user_img'] = news_data.zuozhe.url
    # ret_data['course_name'] = news_data.course.name
    #
    # return ret_route(data=ret_data)

    return render_template('news_tag.html', news_html_tag=orm2dict(news_data))


@news_blue.route("/", methods=['post'])
# @login_required
def add_new():

    news_data = dict(request.json)
    news_data['c_time'] = int(time.time())
    # news_data['user_id'] = current_user.id
    news_data['user_id'] = 1
    db.session.add(News(**news_data))
    db.session.commit()
    return ret_route(2000)


@news_blue.route("/edit", methods=['get'])
def add_edit():
    return render_template('md_edit.html')


@news_blue.route("/types", methods=['get'])
def get_types():
    return ret_route(data=list(News.types_column))